package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.BDealerService;
import cn.huiyunche.base.service.mappers.BDealerMapper;
import cn.huiyunche.base.service.model.BDealer;
import cn.huiyunche.base.service.model.BDealerExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @FileName: cn.huiyunche.service.base.tms.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 下午12:52
 */
@Service
public class BDealerServiceImpl implements BDealerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BDealerServiceImpl.class);

    @Autowired
    private BDealerMapper bDealerMapper;

    @Override
    public Integer getIdByConditions(String dealerCode, String dealerName) {
        LOGGER.info("getIdByConditions params : {}, {}", dealerCode, dealerName);
        if (StringUtils.isBlank(dealerCode)) {
            LOGGER.error("getIdByConditions param dealerCode must not be null");
            throw new IllegalArgumentException("经销商编码不能为空");
        }
        if (StringUtils.isBlank(dealerName)) {
            LOGGER.error("getIdByConditions param dealerName must not be null");
            throw new IllegalArgumentException("经销商名称不能为空");
        }

        BDealerExample example1 = new BDealerExample();
        example1.createCriteria().andDealerCodeEqualTo(dealerCode).andDealerNameEqualTo(dealerName);

        BDealerExample example2 = new BDealerExample();
        example2.createCriteria().andDealerCodeEqualTo(dealerCode);

        List<BDealer> list = bDealerMapper.selectByExample(example1);
        if (CollectionUtils.isEmpty(list)) {
            list = bDealerMapper.selectByExample(example2);
            if (CollectionUtils.isNotEmpty(list)) {
                BDealer bDealer = list.get(0);
                bDealer.setDealerName(dealerName);
                bDealerMapper.updateByPrimaryKeySelective(bDealer);
                return bDealer.getId();
            }
        } else {
            return list.get(0).getId();
        }

        BDealer bDealer = new BDealer();
        bDealer.setDealerCode(dealerCode);
        bDealer.setDealerName(dealerName);
        bDealerMapper.insertSelective(bDealer);

        return bDealer.getId();
    }
}
